import { Injectable, Inject, HttpException, HttpStatus } from '@nestjs/common';
import { PrismaService } from '@/prisma/prisma.service';
import { PaginationService } from '@/hooks/usePagination';

@Injectable()
export class CommunityControlService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  @Inject(PaginationService)
  private readonly paginationService: PaginationService;

  async getCommunityList(pageNum, pageSize, userId, username, status, sort) {
    const userObject = await this.prisma.user.findMany({
      select: {
        id: true,
      },
      where: {
        id: userId,
        username: {
          contains: username,
        },
      },
    });
    const uids = userObject.map((item) => item.id);

    const query = {
      where: {
        status,
        userId: {
          in: uids,
        },
      },
      include: {
        community_img: {
          select: {
            img: true,
          },
        },
        User: {
          select: {
            username: true,
            avatar: true,
          },
        },
      },
      orderBy: {
        createdAt: sort,
      },
    };

    const res = await this.paginationService.paginate(
      'community',
      query,
      pageNum,
      pageSize,
    );
    return res;
  }

  async getCommunityById(id: number) {
    const res = await this.prisma.community.findUnique({
      where: {
        id,
      },
      include: {
        community_img: {
          select: {
            img: true,
          },
        },
        User: {
          select: {
            username: true,
            avatar: true,
          },
        },
      },
    });

    if (!res) {
      throw new HttpException('该动态不存在', HttpStatus.BAD_REQUEST);
    }
    return res;
  }

  async examineCommunity(id: number, status: number) {
    await this.getCommunityById(id);

    const res = await this.prisma.community.update({
      where: {
        id,
      },
      data: {
        status,
      },
    });
    return res;
  }

  async getStarInfo(userId: number, communityId: number) {
    const res = await this.prisma.user_community.findFirst({
      where: {
        userId,
        communityId,
      },
    });
    return !!res;
  }
}
